import ast
import datetime
import json
import random
import re
import sys
from utils.hash import md5
from utils.tools import TushanCRUD, is_blank, process_error
from fastapi import APIRouter, Header, Depends, Request, Response
from pydantic import BaseModel
from models.requests import PageRequest, UserAdd
from components.db import prisma
from fastapi_jwt_auth import AuthJWT


from prisma.errors import UniqueViolationError
from fastapi_jwt_auth.exceptions import MissingTokenError, JWTDecodeError

from utils.resp import BusinessException, resp_err, resp_json, resp_ok, resp_data
from utils.time import current_datetime

from components.db import curd_service

# prisma 高级
# https://prisma-client-py.readthedocs.io/en/stable/getting_started/partial-types/


tuashan_admin_router = APIRouter(prefix="/api/admin")



# api_route 支持多方法
@tuashan_admin_router.api_route(path="/{resource_id}", methods=["GET", "POST"])
async def tushan_admin_process(resource_id: str, request: Request, response: Response):
    try:
        
       # https://blog.csdn.net/qq_33801641/article/details/120610434
    #    res = {
    #        "port": request.client.port,
    #         # 请求方法
    #         "method": request.method,
    #         # 请求路径
    #         "base_url": request.base_url,
    #         # request headers
    #         "headers": request.headers,

    #         "query_params": request.query_params,
            
    #         "path_params": request.path_params,
    #         "resource_id": request.path_params.get("resource_id"),

    #         # 获取 Request Body
    #         # "body": await request.json(),
    #         # "body_bytes": await request.body()
    #     }
       
       method = request.method
       prisma_table = curd_service.get_resource(resource_id)

       if prisma_table is None:
           return resp_err("resource not exist")
       else:
           res = None

           if "GET" == method:
               (count, res) = await curd_service.listAction(prisma_table, request)
                # 需要添加 Access-Control-Expose-Headers
               response.headers["Access-Control-Expose-Headers"] = str("*")
               response.headers["x-total-Count"] = str(count)

           if "POST" == method:
               res = await curd_service.postAction(prisma_table, request)
            
           return res
    except Exception as e:
        process_error(e)






@tuashan_admin_router.api_route(path="/{resource_id}/{id}", methods=["PUT", "DELETE"])
async def tushan_admin_process_ops(resource_id: str, id: str, request: Request):
    try:
       method = request.method
       
       if is_blank(id) or not id.isdigit():
           return resp_err("id is error")
       
       prisma_table = curd_service.get_resource(resource_id)
       if prisma_table is None:
           return resp_err("resource not exist")
       
       else:
           res = None

           if "PUT" == method:
               res = await curd_service.putAction(prisma_table, id, request)

           if "DELETE" == method:
               res = await curd_service.deleteAction(prisma_table, id, request)

            
           return res
    except Exception as e:
        process_error(e)
